/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.*;
import com.cashmate.hibernate.pojo.Areas;
import com.cashmate.hibernate.pojo.Borrowers;
import com.cashmate.hibernate.pojo.Branches;
import com.cashmate.hibernate.pojo.Documents;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Loans;
import com.cashmate.hibernate.pojo.Loanverification;
import com.cashmate.hibernate.pojo.Products;
import com.cashmate.hibernate.pojo.Request;
import com.opensymphony.xwork2.ActionSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

/**
 *
 * @author Lee
 */
public class AddLoanVerification extends ActionSupport {

    private BorrowerDAO bord = (BorrowerDAO) ServletActionContext.getServletContext().getAttribute("borrowerDAO");
    private BranchDAO brd = (BranchDAO) ServletActionContext.getServletContext().getAttribute("branchDAO");
    private EmployeeDAO emd = (EmployeeDAO) ServletActionContext.getServletContext().getAttribute("employeeDAO");
    private AreaDAO ard = (AreaDAO) ServletActionContext.getServletContext().getAttribute("areaDAO");
    private ProductDAO pd = (ProductDAO) ServletActionContext.getServletContext().getAttribute("productDAO");
    private LoanverificationDAO lvd = (LoanverificationDAO) ServletActionContext.getServletContext().getAttribute("loanverificationDAO");
    private LoansDAO loanDAO = (LoansDAO) ServletActionContext.getServletContext().getAttribute("loansDAO");
    private RequestDAO requestDAO = (RequestDAO) ServletActionContext.getServletContext().getAttribute("requestDAO");
    private DocumentDAO documentDAO = (DocumentDAO) ServletActionContext.getServletContext().getAttribute("documentDAO");
    private String loanverificationcode;
    private String borid;//borrowerid if renew
    private String loantype;
    private String loanclassification;//productid
    private String loanterm;
    private String amountapplied;
    private String amountrequested;
    private String firstname;
    private String middlename;
    private String lastname;
    private String documenttype;
    private String documentdate;
    private String documentno;
    private String status;
    private String selectedArea;//areacode
    private String streetaddress;
    private String barangay;
    private String cityormunicipality;
    private String province;
    private String selectedBranch;//branchcode
    private String employees;//empid
    private String successurl;
    private String actionstatus;
//    private String collaterals;
    private String creditrating, amountofstocks, businesstype,
            coborrowerfirstname, coborrowermiddlename, coborrowerlastname,
            coborrowerstreetaddress, coborrowerbarangay, coborrowercityormunicipality,
            coborrowerprovince, previousloanid;
    private SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

    public String getSuccessurl() {
        return successurl;
    }

    public String getActionstatus() {
        return actionstatus;
    }

    public void setActionstatus(String actionstatus) {
        this.actionstatus = actionstatus;
    }

    public void setAmountapplied(String amountapplied) {
        this.amountapplied = amountapplied;
    }

    public void setBarangay(String barangay) {
        this.barangay = barangay;
    }

    public void setBord(BorrowerDAO bord) {
        this.bord = bord;
    }

    public void setCityormunicipality(String cityormunicipality) {
        this.cityormunicipality = cityormunicipality;
    }

    public void setDocumentdate(String documentdate) {
        this.documentdate = documentdate;
    }

    public void setDocumentno(String documentno) {
        this.documentno = documentno;
    }

    public void setDocumenttype(String documenttype) {
        this.documenttype = documenttype;
    }

    public void setEmployees(String employees) {
        this.employees = employees;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public void setLoanclassification(String loanclassification) {
        this.loanclassification = loanclassification;
    }

    public void setLoanterm(String loanterm) {
        this.loanterm = loanterm;
    }

    public void setLoantype(String loantype) {
        this.loantype = loantype;
    }

    public void setLoanverificationcode(String loanverificationcode) {
        this.loanverificationcode = loanverificationcode;
    }

    public void setMiddlename(String middlename) {
        this.middlename = middlename;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public void setSelectedArea(String selectedArea) {
        this.selectedArea = selectedArea;
    }

    public void setSelectedBranch(String selectedBranch) {
        this.selectedBranch = selectedBranch;
    }

    public void setStreetaddress(String streetaddress) {
        this.streetaddress = streetaddress;
    }

    public void setBorid(String borid) {
        this.borid = borid;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setAmountofstocks(String amountofstocks) {
        this.amountofstocks = amountofstocks;
    }

    public void setBusinesstype(String businesstype) {
        this.businesstype = businesstype;
    }

    public void setCoborrowerbarangay(String coborrowerbarangay) {
        this.coborrowerbarangay = coborrowerbarangay;
    }

    public void setCoborrowercityormunicipality(String coborrowercityormunicipality) {
        this.coborrowercityormunicipality = coborrowercityormunicipality;
    }

    public void setCoborrowerfirstname(String coborrowerfirstname) {
        this.coborrowerfirstname = coborrowerfirstname;
    }

    public void setCoborrowerlastname(String coborrowerlastname) {
        this.coborrowerlastname = coborrowerlastname;
    }

    public void setCoborrowermiddlename(String coborrowermiddlename) {
        this.coborrowermiddlename = coborrowermiddlename;
    }

    public void setCoborrowerprovince(String coborrowerprovince) {
        this.coborrowerprovince = coborrowerprovince;
    }

    public void setCoborrowerstreetaddress(String coborrowerstreetaddress) {
        this.coborrowerstreetaddress = coborrowerstreetaddress;
    }

    public void setCreditrating(String creditrating) {
        this.creditrating = creditrating;
    }

    public void setPreviousloanid(String previousloanid) {
        this.previousloanid = previousloanid;
    }

    public void setAmountrequested(String amountrequested) {
        this.amountrequested = amountrequested;
    }

//    public void setCollaterals(String collaterals) {
//        this.collaterals = collaterals;
//    }
    @Action(value = "/add-loanverification", results = {
        @Result(name = "input", location = "/loanapplication.jsp"),
        @Result(name = "success", location = "${successurl}"),
        @Result(name = "error", location = "${successurl}")
    })
    @Override
    public String execute() {
        //retrieve branch, product, area, employees
        //create borrower
        //create loanverification
        Branches branch = (Branches) ServletActionContext.getRequest().getSession().getAttribute("branch");
        successurl = "../../loanapplication.jsp?cat=loanappli";
        Branches b;
        Employees e;
        Areas a;
        Products p;
        Borrowers oldborrower;
        Documents d;
        boolean stat;

        //check if required fields are not empty
        if (loantype.equals("") || loantype.equals("-1")) {
            actionstatus = "Please specify the loan type.";
            return ERROR;
        }
        if (loanclassification.equals("") || loanclassification.equals("-1")) {
            actionstatus = "Please specify the loan classification.";
            return ERROR;
        }
        if (loanterm.equals("")) {
            actionstatus = "Please specify the loan term.";
            return ERROR;
        } else {
            try {
                Integer.parseInt(loanterm);
            } catch (Exception ex) {
                actionstatus = "Please specify a valid loan term.";
                ex.printStackTrace();
                return ERROR;
            }
        }

        if (amountapplied.equals("")) {
            actionstatus = "Please specify the amount applied.";
            return ERROR;
        } else {
            try {
                Integer.parseInt(amountapplied);
            } catch (Exception ex) {
                actionstatus = "Please specify a valid amount applied.";
                ex.printStackTrace();
                return ERROR;
            }
        }
        if (firstname.equals("")) {
            actionstatus = "Please specify the first name.";
            return ERROR;
        }
        if (middlename.equals("")) {
            actionstatus = "Please specify the middle name.";
            return ERROR;
        }
        if (lastname.equals("")) {
            actionstatus = "Please specify the last name.";
            return ERROR;
        }
        if (documenttype.equals("")) {
            actionstatus = "Please specify the document type.";
            return ERROR;
        }
        if (documentdate.equals("")) {
            actionstatus = "Please specify the document date.";
            return ERROR;
        }
        if (documentno.equals("")) {
            actionstatus = "Please specify the document no.";
            return ERROR;
        }
        if (selectedArea.equals("") || selectedArea.equals("-1")) {
            actionstatus = "Please specify the address' barangay.";
            return ERROR;
        }
        if (streetaddress.equals("")) {
            actionstatus = "Please specify the address' streetaddress.";
            return ERROR;
        }
        if (barangay.equals("")) {
            actionstatus = "Please specify the address' barangay.";
            return ERROR;
        }
        if (cityormunicipality.equals("")) {
            actionstatus = "Please specify the address' cityormunicipality.";
            return ERROR;
        }
        if (province.equals("")) {
            actionstatus = "Please specify the address' province.";
            return ERROR;
        }
        if (selectedBranch.equals("")) {
            actionstatus = "Please specify the branch.";
            return ERROR;
        }
        if (employees.equals("")) {
            actionstatus = "Please specify the employee";
            return ERROR;
        }

        //loanapplication's branch, product, area, employees
        try {
            b = brd.getByBranchCode(selectedBranch);
        } catch (Exception ex) {
            b = null;
            actionstatus = "There was an error in setting the branch.";
            ex.printStackTrace();
            return ERROR;
        }

        try {
            p = pd.getByProdName(Integer.parseInt(loanclassification));
        } catch (Exception ex) {
            p = null;
            actionstatus = "There was an error in setting the loan classification.";
            ex.printStackTrace();
            return ERROR;
        }

        try {
            a = ard.getByAreaCode(selectedArea);
        } catch (Exception ex) {
            a = null;
            actionstatus = "There was an error in setting the area.";
            ex.printStackTrace();
            return ERROR;
        }

        try {
            e = emd.getByIdNumber(employees);
        } catch (Exception ex) {
            e = null;
            ex.printStackTrace();
            actionstatus = "There was an error in setting the employee.";
            return ERROR;
        }

        try {
            d = new Documents(documentno, documenttype, documentdate, true);
        } catch (Exception ex) {
            ex.printStackTrace();
            d = null;
            actionstatus = "There was an error in setting the document.";
            return ERROR;
        }
        //if renew
//        System.out.println("BORID" + borid);
        if (borid != null && !borid.equals("")) {
            char[] numbers = borid.toCharArray();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < numbers.length; i++) {
                Character chara = numbers[i];
                if (!Character.isLetter(chara)) {
                    sb.append(chara);
                }
            }
//            System.out.println("Stringbuffer:" + sb);
            int inte = Integer.parseInt(sb.toString());
//            System.out.println("PARSED: " + inte);

            int id = Integer.parseInt(sb.toString());

            try {
                oldborrower = bord.get(id);
            } catch (Exception ex) {
                ex.printStackTrace();
                oldborrower = null;
                actionstatus = "There was an error in setting the borrower.";
                return ERROR;
            }

            Loans prevloan = null;
            if (!previousloanid.equals("")) {
                try {
                    int prevloanid = Integer.parseInt(previousloanid);
                    prevloan = loanDAO.get(prevloanid);
                } catch (Exception l) {
                    l.printStackTrace();
                }
            }



            Loanverification lv = new Loanverification(d, oldborrower, e, loantype, p, loanverificationcode, Integer.parseInt(loanterm), Integer.parseInt(amountapplied), Integer.parseInt(amountrequested), null);
            lv.setLoanverificationcode(loanverificationcode);
            lv.setWithaf("n");
            lv.setWithci("n");
            lv.setWithap("n");
            lv.setWithcm("n");
            lv.setStatus(status);
            lv.setCreditrating(Integer.parseInt(creditrating));
            lv.setAmountofstocks(Integer.parseInt(amountofstocks));
            lv.setCoborrowerbarangay(coborrowerbarangay);
            lv.setCoborrowercityormunicipality(coborrowercityormunicipality);
            lv.setCoborrowerfirstname(coborrowerfirstname);
            lv.setCoborrowerlastname(coborrowerlastname);
            lv.setCoborrowermiddlename(coborrowermiddlename);
            lv.setCoborrowerprovince(coborrowerprovince);
            lv.setCoborrowerstreetaddress(coborrowerstreetaddress);
            lv.setBusinesstype(businesstype);
//            lv.setTypeofcollaterals(collaterals);
            if (prevloan != null) {
                lv.setPreviousloan(prevloan);
            }

//            System.out.println(creditrating + "_" + amountofstocks + "_" + businesstype + "_"
//                    + coborrowerfirstname + "_" + coborrowermiddlename + "_" + coborrowerlastname + "_"
//                    + coborrowerstreetaddress + "_" + coborrowerbarangay + "_" + coborrowercityormunicipality + "_"
//                    + coborrowerprovince + "_" + previousloanid);

//            ajflsjkf

            try {
                stat = lvd.addForOld(d, lv);

                if (status.equals("posted")) {
//                    Request r = null;
//                    Request req = new Request();
//                    req.setStatus("Verified");
//                    req.setRequestdate(formatter.format(new Date()));
//                    req.setBranches(branch);
//                    req.setEmployees((Employees) ServletActionContext.getRequest().getSession().getAttribute("employee"));
//                    requestDAO.insert(req);
//
//                    Documents doc = new Documents();
//                    doc.setDocumenttype("Loan Request");
//                    doc.setDocumentdate(formatter.format(new Date()));
//                    doc.setDocumentno(branch.getBranchcode() + req.getRequestid());
//                    doc.setIsactive(true);
//                    documentDAO.insert(doc);
//
//                    req.setDocuments(doc);
//                    requestDAO.update(req);
//                    r = req;

                    lv.setStatus("Posted");
//                    lv.setRequest(r);
                    lvd.update(lv);
                }

                if (stat == true) {
                    if (status.equals("saved")) {
                        actionstatus = "Loan application saved for new borrower!";
                    }
                    if (status.equals("posted")) {
                        actionstatus = "Loan application posted for new borrower!";
                    }
                    return SUCCESS;
                } else {
                    actionstatus = "Server error. Please try again.";
                    return ERROR;
                }
            } catch (Exception g) {
                g.printStackTrace();
                actionstatus = ("Error in saving loan verification for old");
                return ERROR;
            }

//            private Employees employees;
//    private String loanverificationcode;
//            Borrowers borrower, Employees employees, String loantype, Products products, int loanterm, int amountapplied

            //else if new
        } else {
            Borrowers newborrower = new Borrowers(firstname, middlename, lastname, streetaddress, barangay, cityormunicipality, province);
            newborrower.setIsactive(true);
            newborrower.setBranches(b);
            newborrower.setAreas(a);

            Loanverification lv = new Loanverification(d, newborrower, e, loantype, p, loanverificationcode, Integer.parseInt(loanterm), Integer.parseInt(amountapplied), Integer.parseInt(amountrequested), null);
            lv.setLoanverificationcode(loanverificationcode);
            lv.setWithaf("n");
            lv.setWithci("n");
            lv.setWithap("n");
            lv.setWithcm("n");
            lv.setStatus(status);
            lv.setCreditrating(Integer.parseInt(creditrating));
            lv.setAmountofstocks(Integer.parseInt(amountofstocks));
            lv.setCoborrowerbarangay(coborrowerbarangay);
            lv.setCoborrowercityormunicipality(coborrowercityormunicipality);
            lv.setCoborrowerfirstname(coborrowerfirstname);
            lv.setCoborrowerlastname(coborrowerlastname);
            lv.setCoborrowermiddlename(coborrowermiddlename);
            lv.setCoborrowerprovince(coborrowerprovince);
            lv.setCoborrowerstreetaddress(coborrowerstreetaddress);
            lv.setBusinesstype(businesstype);

            try {
                stat = lvd.addForNew(d, newborrower, lv);
                
                if (status.equals("posted")) {
//                Request r = null;
//                Request req = new Request();
//                req.setStatus("Verified");
//                req.setRequestdate(formatter.format(new Date()));
//                req.setBranches(branch);
//                req.setEmployees((Employees) ServletActionContext.getRequest().getSession().getAttribute("employee"));
//                requestDAO.insert(req);
//
//                Documents doc = new Documents();
//                doc.setDocumenttype("Loan Request");
//                doc.setDocumentdate(formatter.format(new Date()));
//                doc.setDocumentno(branch.getBranchcode() + req.getRequestid());
//                doc.setIsactive(true);
//                documentDAO.insert(doc);
//
//                req.setDocuments(doc);
//                requestDAO.update(req);
//                r = req;

                lv.setStatus("Posted");
//                lv.setRequest(r);
                lvd.update(lv);
                }
                if (stat == true) {
                    if (status.equals("saved")) {
                        actionstatus = "Loan application saved for new borrower!";
                    }
                    if (status.equals("posted")) {
                        actionstatus = "Loan application posted for new borrower!";
                    }

                    return SUCCESS;
                } else {
                    actionstatus = "Server error. Please try again.";
                    return ERROR;
                }
            } catch (Exception g) {
                g.printStackTrace();
                actionstatus = ("Error in saving loan verification for old");
                return ERROR;
            }

        }
    }
}
